import CartService from "@/services/cart-service";
import dbProvider from "@/lib/db";

// 处理购物车相关请求的主函数
export async function handleRequest(req, res) {
  const method = req.method;

  switch (method) {
    case 'POST':
      return addToCart(req, res);
    case 'PATCH':
      return updateCart(req, res);
    case 'DELETE':
      return clearCart(req, res);
    case 'GET':
      return getCart(req, res);
    default:
      res.setHeader('Allow', ['POST', 'PATCH', 'DELETE', 'GET']);
      res.status(405).end(`Method ${method} Not Allowed`);
  }
}

// 添加商品到购物车
async function addToCart(req, res) {
  const { userId, productId, quantity } = await req.json();
  const cartService = CartService.getInstance(dbProvider);

  try {
    await cartService.addToCart(userId, productId, quantity);
    res.status(200).json({ message: "商品已添加到购物车" });
  } catch (error) {
    res.status(500).json({ message: "添加商品到购物车时出错", error });
  }
}

// 更新购物车商品数量
async function updateCart(req, res) {
  const { userId, productId, quantity } = await req.json();
  const cartService = CartService.getInstance(dbProvider);

  try {
    await cartService.updateCart(userId, productId, quantity);
    res.status(200).json({ message: "购物车已更新" });
  } catch (error) {
    res.status(500).json({ message: "更新购物车时出错", error });
  }
}

// 清空购物车
async function clearCart(req, res) {
  const { userId } = await req.json();
  const cartService = CartService.getInstance(dbProvider);

  try {
    await cartService.clearCart(userId);
    res.status(200).json({ message: "购物车已清空" });
  } catch (error) {
    res.status(500).json({ message: "清空购物车时出错", error });
  }
}

// 获取用户购物车内容
async function getCart(req, res) {
  const { userId } = req.query;
  const cartService = CartService.getInstance(dbProvider);

  try {
    const cartItems = await cartService.getCart(userId);
    res.status(200).json(cartItems);
  } catch (error) {
    res.status(500).json({ message: "获取购物车内容时出错", error });
  }
}

export default handleRequest;
